
<!-- 广告投放方案的数据统计 -->
<template>
  <!-- 这个是显示整体统计页面的组件 -->
  <div>
    <div class="overview-action toolbar-btn-action">
      <div class="searchBox">
        <el-select
          v-model="adplaceId"
          placeholder="全部广告物料"
          size="mini"
          v-on:change="searchSubmit"
          :style="{ width: '30%' }"
        >
          <el-option
            v-for="(item, index) in selectOptions"
            :key="index"
            :label="item.label"
            :value="item.value"
            :disabled="item.disabled"
          ></el-option>
        </el-select>

        <el-date-picker
          type="daterange"
          v-model="formData.timelimit"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          :style="{ width: '65%' }"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          range-separator="至"
          size="mini"
          v-on:change="searchSubmit"
          :picker-options="pickerOptions"
        ></el-date-picker>
        <!--    v-on:change="searchSubmit"
        <el-button icon="el-icon-search" size="mini" @click="searchSubmit"
           :style="{float:'right'}"> 搜索 </el-button>-->
      </div>
      <!-- {# 功能按钮#} -->
      <div class="right-head">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item>报告</el-breadcrumb-item>
          <el-breadcrumb-item> 投放报告</el-breadcrumb-item>
          <el-breadcrumb-item>
            <span style="color: red"
              >刷新倒计时 <i>{{ minute }}</i> ：<i>{{ seconds }}</i></span>
               <span @click="navigateTimemer">{{timemerButton}}</span>
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>
    <!-- 总概览数据 -->
    <div v-loading="tableLoading">
      <div class="overview-total">
        <ul class="general-detail">
          <li class="detail-item imp">
            <p class="number">
              <span>{{ totals.nb_impressions }}</span>
            </p>
            <p class="tipstxt">
              <span>展现量</span
              ><span class="icon-tips el-icon-question"></span>
            </p>
          </li>
          <li class="detail-item int">
            <p class="number">
              <span>{{ totals.nb_interactions }}</span>
            </p>
            <p class="tipstxt"><span>点击量</span></p>
          </li>
          <li class="detail-item bill">
            <p class="number">
              <span>{{ totals.interaction_rate }}%</span>
            </p>
            <p class="tipstxt"><span>点击率</span></p>
          </li>
          <li class="detail-item income">
            <p class="number">
              <span> {{ totals.nb_visits }}</span>
            </p>
            <p class="tipstxt">
              <span>收入</span><span class="icon-tips el-icon-question"></span>
            </p>
          </li>
        </ul>
      </div>
      <!-- 曲线图 -->
      <h3>走势图：</h3>
      <ve-line :data="chartData"></ve-line>
      <!-- {# 网站和app的管理列表 #} -->
      <!-- @selection-change="handleSelectionChange" -->
    </div>
    <h3>广告物料数据：</h3>
    <div class="table-responsive" v-loading="tableLoading">
      <el-table
        v-bind:data="
          tablelist.slice((currentPage - 1) * pageSize, currentPage * pageSize)
        "
        border
        ref="multipleTable"
        style="width: 100%"
      >
        <el-table-column prop="label" label="物料[ID]名称" width="280">
        </el-table-column>
        <el-table-column prop="nb_impressions" label="展现量" width="130">
        </el-table-column>

        <el-table-column prop="nb_interactions" label="点击量">
        </el-table-column>

        <el-table-column prop="interaction_rate" label="点击率" width="">
          <template slot-scope="scope">
            <span> {{ scope.row.interaction_rate | filter_rate }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="ecpm" label="eCPM" width="90"> </el-table-column>
        <el-table-column prop="cpc" label="CPC" width=""> </el-table-column>

        <el-table-column prop="nb_visits" label="访问量"> </el-table-column>
      </el-table>

      <el-pagination
        style="margin-top: 10px"
        background
        :page-size="pageSize"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        @size-change="handleSizeChange"
        :page-sizes="[5, 10, 20, 30, 50, 70, 100]"
        layout="prev, pager, next,total,jumper,sizes"
        :total="tablelist.length"
      >
      </el-pagination>
    </div>
  </div>
</template>
<script>
import ReportApi from "./ReportApi.js";

// var EventProxy = require("eventproxy");

export default {
  components: {},
  props: ["idmedias"],
  data: function () {
    return {
      tablelist: [], //table数据
      formData: {
        timelimit: undefined,
      },
      totals: {
        nums: 0,
        nb_visits: 0,
        sum_daily_nb_uniq_visitors: 0,
        nb_impressions: 0,
        nb_interactions: 0,
        interaction_rate: 0,
      },
      currentUserLogin:"",
      //倒计时
      timemerButton:"",
      timemer: undefined,
      countdownTime: 1, //总的倒计时时间
      hour: 0,
      minute: 0,
      seconds: 0,
      //广告位选项下拉
      adplaceId: 0, //指定某个广告位ID
      selectOptions: [{ value: 0, label: "全部物料", disabled: false }],
      pageSize: 10,
      currentPage: 1,
      tableLoading: false,
      chartData: {
        columns: ["日期", "展现数", "点击数", "点击率"],
        rows: [],
      },
      // 设置日历选择的 快速选择 最近一周，一个月，三个月
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  filters: {
    filter_rate(value) {
      return Math.floor(value * 100) / 100 + "%";
    },
  },
  created() {
     if(this.idmedias>0){
           this.adplaceId =  parseInt(this.idmedias);
         }
    // 当前时间
    var nowDate = new Date();
    var startdate = new Date(nowDate.getTime() - 7 * 24 * 60 * 60 * 1000);

    this.formData.timelimit = [
      this.getNowFormatDate(startdate),
      this.getNowFormatDate(nowDate),
    ];

    this.submitForm(true);
  },
  methods: {
    // 倒计时
    navigateTimemer(){
        if(this.timemerButton == '暂停'){
            clearTimeout(this.timemer );
            clearTimeout(ReportApi.timemer) ;
            this.timemerButton = '重启'
        }else{
          this.setTimer();
        }
      	
    },
    setTimer() {
      let _this = this;
       this.timemerButton =  '暂停';
      ReportApi.setTimeData(this, this.countdownTime * 60 * 1000);
      this.timemer = setTimeout(function () {
        ReportApi.timeCountDown(
          _this,
          _this.countdownTime * 60 * 1000,
          function () {
            _this.submitForm( false );
          }
        );
      }, 1000);
    },
    //分页
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
    },
    getNowFormatDate(date) {
      var seperator1 = "-";
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate;
      return currentdate;
    },
    // 搜索关键词和日期更改提交
    searchSubmit(){
          clearTimeout(this.timemer );
          clearTimeout(ReportApi.timemer) ;
          this.submitForm( true);
    },
    submitForm( showLoading) {
      // 获取曲线图数据
      this.tableLoading = showLoading;
      //获取开始时间和结束时间的间隔天数，用来判断曲线图 返回的区间是 日年周月，
      var days = this.getDaysBetween(
        this.formData.timelimit[0],
        this.formData.timelimit[1]
      );

      ReportApi.reportAdsPlaceRange({
        'startdate': this.formData.timelimit[0],
        'nowdate': this.formData.timelimit[1],
        'days': days,
        'type': "medias",
        'mediasId': this.adplaceId,
         'currentUserLogin': this.currentUserLogin,
      }).then((data) => {
        //console.log(data)
        var rows = [];
        for (var i in data) {
          rows.push({
            日期: "" + data[i]["label"] + "",
            展现数: data[i]["nb_impressions"],
            点击数: data[i]["nb_interactions"],
            点击率: data[i]["interaction_rate"],
          });
        }
        this.chartData.rows = rows;
      });
      // 获取汇总数据和table数据
      ReportApi.mediasOverview({
        'startdate': this.formData.timelimit[0],
        'nowdate': this.formData.timelimit[1],
        "mediasId": this.adplaceId,
         'currentUserLogin': this.currentUserLogin,
      }).then((data) => {
        this.tableLoading = false;
        this.setTimer();
        this.totals = data.total;
        this.tablelist = data.tablelist;
        this.currentUserLogin =  data.currentUserLogin;//当前登录用户
        if (this.selectOptions.length == 1) {
          var tmp = [{ value: 0, label: "全部广告物料", disabled: false }];
          for (var i in data.items) {
            tmp.push({
              value: data.items[i]["id"],
              label:
                "[" +
                data.items[i]["id"] +
                "]" +
                data.items[i]["name"] +
                "[" +
                data.items[i]["width"] +
                "*" +
                data.items[i]["height"] +
                "]",
              disabled: false,
            });
          }
          this.selectOptions = tmp;
        }
      });
    },
    /**
     * 计算两个日期之间的天数
     * @param dateString1  开始日期 yyyy-MM-dd
     * @param dateString2  结束日期 yyyy-MM-dd
     * @returns {number} 如果日期相同 返回一天 开始日期大于结束日期，返回0
     */
    getDaysBetween(dateString1, dateString2) {
      var startDate = Date.parse(dateString1);
      var endDate = Date.parse(dateString2);
      if (startDate > endDate) {
        return 0;
      }
      if (startDate == endDate) {
        return 1;
      }
      var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
      return days;
    },
  },
};
</script>
